package io.kiki.sba.registry.client.task;

import io.kiki.sba.registry.client.api.Register;
import io.kiki.sba.registry.client.provider.AbstractInternalRegister;
import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Setter
@Getter
public class TaskEventQueue implements Iterable<TaskEvent> {

    private final ConcurrentMap<String, TaskEvent> map = new ConcurrentHashMap<String, TaskEvent>();


    @Override
    public Iterator<TaskEvent> iterator() {
        List<TaskEvent> taskList = new ArrayList<TaskEvent>(map.values());
        Collections.sort(taskList);
        return taskList.iterator();
    }


    public void cleanCompletedTasks() {
        List<String> taskList = new ArrayList<String>(map.keySet());
        for (String key : taskList) {
            TaskEvent event = map.get(key);
            AbstractInternalRegister r = (AbstractInternalRegister) event.getSource();
            if (r.isDone()) {
                map.remove(key, event);
            }
        }
        map.size();
    }


    public void put(TaskEvent taskEvent) {
        Register register = taskEvent.getSource();
        String key = register.getRegistId();
        map.put(key, taskEvent);
    }


    public void putAll(List<TaskEvent> list) {
        for (TaskEvent event : list) {
            put(event);
        }
    }


    public boolean isEmpty() {
        return map.isEmpty();
    }
}
